<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:p="http://primefaces.org/ui"
      xmlns:fb="http://ogp.me/ns/fb">
    <h:head>
        <title>Fever invitator &amp; plan search</title>

        <link href="styleQuery.css" type="text/css" rel="stylesheet" />
    </h:head>
    <h:body>
        <h2>Invitator &amp; Plan Search</h2>
        <script src="//connect.facebook.net/es_ES/all.js"></script>
        <script>
            window.fbAsyncInit = function() {
                FB.init({
                    //appId      : '1388008284748084', // App ID
                    appId      : '212044188860269', // App ID
                    //channelUrl : '//feverapp.herokuapp.com', // Channel File
                    status     : true, // check login status
                    cookie     : true, // enable cookies to allow the server to access the session
                    xfbml      : true  // parse XFBML
                });

                // Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
                // for any authentication related change, such as login, logout or session refresh. This means that
                // whenever someone who was previously logged out tries to log in again, the correct case below 
                // will be handled. 
                FB.Event.subscribe('auth.authResponseChange', function(response) {
                    // Here we specify what we do with the response anytime this event occurs. 
                    if (response.status === 'connected') {
                        // The response object is returned with a status field that lets the app know the current
                        // login status of the person. In this case, we're handling the situation where they 
                        // have logged in to the app.
                        testAPI();
                    } else if (response.status === 'not_authorized') {
                        // In this case, the person is logged into Facebook, but not into the app, so we call
                        // FB.login() to prompt them to do so. 
                        // In real-life usage, you wouldn't want to immediately prompt someone to login 
                        // like this, for two reasons:
                        // (1) JavaScript created popup windows are blocked by most browsers unless they 
                        // result from direct interaction from people using the app (such as a mouse click)
                        // (2) it is a bad experience to be continually prompted to login upon page load.
                        FB.login();
                    } else {
                        // In this case, the person is not logged into Facebook, so we call the login() 
                        // function to prompt them to do so. Note that at this stage there is no indication
                        // of whether they are logged into the app. If they aren't then they'll see the Login
                        // dialog right after they log in to Facebook. 
                        // The same caveats as above apply to the FB.login() call here.
                        FB.login();
                    }
                });
            };

            // Load the SDK asynchronously
            (function(d){
                var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
                if (d.getElementById(id)) {return;}
                js = d.createElement('script'); js.id = id; js.async = true;
                js.src = "//connect.facebook.net/en_US/all.js";
                ref.parentNode.insertBefore(js, ref);
            }(document));

            // Here we run a very simple test of the Graph API after login is successful. 
            // This testAPI() function is only called in those cases. 
            function testAPI() {
                console.log('Welcome!  Fetching your information.... ');
                FB.api('/me', function(response) {
                    console.log('Good to see you, ' + response.name + '.');
                });
            }
        </script>

        <div id="fb-root">
            <fb:login-button show-faces="true" width="100" max-rows="1"></fb:login-button>
        </div>
        <br/>

        <p:tabView id="tabView">
            <h:outputText id="bc" value="Bye" />
            <p:tab id="tabInvitator" title="Invitator">
                <h:form id="formInvitator">  
                    <p:panel id="panelInvitator" header="Plan invitator" style="margin-bottom:10px;">  
                        <h7>Choose a plan and invite your friends.</h7>
                        <br/>
                        <br/>
                        <h:panelGrid columns="4" cellpadding="5">
                            <h:outputText value="Plans to invite: " />
                            <p:selectOneMenu id="plansSelect" value="#{feverController.selectedPlan}" filter="true" filterMatchMode="contains" effect="fade">  
                                <f:selectItem itemLabel="-" itemValue="" />  
                                <f:selectItems value="#{feverController.plans}"/>
                            </p:selectOneMenu>

                            <h:outputText value="Hide people who have already been invited to this plan" />
                            <p:selectBooleanCheckbox value="#{feverController.hidePlans}"/>

                            <h:outputText value="Gender: " />
                            <p:selectOneMenu id="genderSelect" value="#{feverController.selectedGenderInvitator}" effect="fade">  
                                <f:selectItem itemLabel="-" itemValue="" />
                                <f:selectItems value="#{feverController.genderInvitator}"/>
                            </p:selectOneMenu>

                            <h:outputText value="Referral: " />
                            <p:selectOneMenu id="contactsSelect" value="#{feverController.selectedContactInvitator}" effect="fade">  
                                <f:selectItem itemLabel="-" itemValue="" />  
                                <f:selectItems value="#{feverController.contactsInvitator}"/>
                            </p:selectOneMenu>

                            <h:outputText value="Age range: " />
                            <h:panelGrid columns="1" style="margin-bottom:10px">                      
                                <h:outputText id="displayRange" value="Between #{feverController.age1} and #{feverController.age2} (inclusive)"/>                      
                                <p:slider for="txt6,txt7" display="displayRange" style="width:400px" range="true" 
                                          minValue="#{feverController.rangeAge1}" maxValue="#{feverController.rangeAge2}" displayTemplate="Between {min} and {max}"/>  
                            </h:panelGrid>  
                            <h:inputHidden id="txt6" value="#{feverController.age1}" />  
                            <h:inputHidden id="txt7" value="#{feverController.age2}" />  

                            <h:outputText value="Style: " />
                            <p:selectCheckboxMenu id="styleSelect" value="#{feverController.selectedStylesInvitator}" label="style" panelStyle="width:150px">  
                                <f:selectItems value="#{feverController.styleInvitator}" />  
                            </p:selectCheckboxMenu>

                            <h:outputText value="Influence: " />
                            <p:selectOneMenu id="influenceSelect" value="#{feverController.selectedInfluenceInvitator}" effect="fade">  
                                <f:selectItem itemLabel="-" itemValue="" />  
                                <f:selectItems value="#{feverController.influenceInvitator}"/>
                            </p:selectOneMenu>

                            <h:outputText value="Image: " />
                            <p:selectCheckboxMenu id="imageSelect" value="#{feverController.selectedImagesInvitator}" label="image" panelStyle="width:200px">  
                                <f:selectItems value="#{feverController.imageInvitator}" />  
                            </p:selectCheckboxMenu>

                            <h:outputLabel for="firstnameInvitator" value="Firstname: " />  
                            <p:inputText id="firstnameInvitator"   
                                         value="#{feverController.nameInvitator}" label="Firstname">
                            </p:inputText>  

                            <h:outputLabel for="surnameInvitator" value="Last Name: " />  
                            <p:inputText id="surnameInvitator"   
                                         value="#{feverController.surnameInvitator}" label="Lastname"/>

                            <h:outputText value="Match case (for name/surname)" />
                            <p:selectBooleanCheckbox value="#{feverController.matchCase}"/>
                        </h:panelGrid>  
                    </p:panel>

                    <p:commandButton actionListener="#{feverController.userExcelInvitator}" update="panelInvitator,tableInvitator" id="iconOnlyInvitator" icon="ui-icon-search" title="Search user(s)" value="Search"/>

                    <br/>
                    <h7>To select multiple users, hold 'Ctrl' key pressed and select. ('Alt' for multiple selection in a row).</h7>
                    <br/>
                    <h7>STEPS. 1: Select user(s). 2: Add to Plan. 3: Invite</h7>

                    <p:dataTable id="tableInvitator" value="#{feverController.userExcelInvitator}" var="user" sortMode="multiple" rows="20" paginator="true" paginatorAlwaysVisible="false"
                                 selectionMode="multiple" selection="#{feverController.selectedExcelUsers}" rowKey="#{user.facebookId}">
                        <f:facet name="header">
                            <p:commandButton value="Add to Plan" actionListener="#{feverController.updateDatabase}" id="iconOnlyUpdate" icon="ui-icon-plusthick" title="Update database with invitations"/>
                        </f:facet>
                        <f:facet name="header">
                            <p:commandButton value="Invite" icon="ui-icon-comment" update=":inv,:tabView:formInvitator" title="Invite user(s) to the selected plan" oncomplete="confirmation.show()"/>
                        </f:facet>

                        <p:column sortBy="#{user.contacto}">
                            <f:facet name="header">
                                <h:outputText value="Referral"></h:outputText>
                            </f:facet>
                            <h:outputText value="#{user.contacto}"></h:outputText>
                        </p:column>
                        <p:column sortBy="#{user.nombre}">
                            <f:facet name="header">
                                <h:outputText value="Name"></h:outputText>
                            </f:facet>
                            <h:outputText value="#{user.nombre}"></h:outputText>
                        </p:column>
                        <p:column sortBy="#{user.apellidos}">
                            <f:facet name="header">
                                <h:outputText value="Last Name"></h:outputText>
                            </f:facet>
                            <h:outputText value="#{user.apellidos}"></h:outputText>
                        </p:column>
                        <p:column sortBy="#{user.sexo}">
                            <f:facet name="header">
                                <h:outputText value="Gender"></h:outputText>
                            </f:facet>
                            <h:outputText value="#{user.sexo}"></h:outputText>
                        </p:column>
                        <p:column sortBy="#{user.edad}">
                            <f:facet name="header">
                                <h:outputText value="Age"></h:outputText>
                            </f:facet>
                            <h:outputText value="#{user.edad}"></h:outputText>
                        </p:column>
                        <p:column sortBy="#{user.estilo}">
                            <f:facet name="header">
                                <h:outputText value="Style"></h:outputText>
                            </f:facet>
                            <h:outputText value="#{user.estilo}"></h:outputText>
                        </p:column>
                        <p:column sortBy="#{user.influencia}">
                            <f:facet name="header">
                                <h:outputText value="Influence"></h:outputText>
                            </f:facet>
                            <h:outputText value="#{user.influencia}"></h:outputText>
                        </p:column>
                        <p:column sortBy="#{user.imagen}">
                            <f:facet name="header">
                                <h:outputText value="Image"></h:outputText>
                            </f:facet>
                            <h:outputText value="#{user.imagen}"></h:outputText>
                        </p:column>
                        <p:column sortBy="#{user.facebookId}">
                            <f:facet name="header">
                                <h:outputText value="Facebook Id"></h:outputText>
                            </f:facet>
                            <h:outputText value="#{user.facebookId}"></h:outputText>
                        </p:column>
                    </p:dataTable> 

                    <p:confirmDialog id="confirmDialog" message="Do you want to invite these users to this plan?"  
                                     header="Invite people to plan" severity="info" widgetVar="confirmation">
                        <h:outputText id="inv2" value="#{feverController.selectedNameLast}"/>
                        <br/>
                        <p:commandButton id="confirm" value="Yes Sure" onclick="sendRequestViaMultiFriendSelectorSelected(); confirmation.hide();" type="button"/>
                        <p:commandButton id="decline" value="Not Yet" onclick="confirmation.hide()" type="button" />   

                    </p:confirmDialog>
                </h:form>
            </p:tab>

            <p:tab id="tabSearch" title="Plan search">
                <h:form id="form">  
                    <p:panel id="panel" header="Plan search by person" style="margin-bottom:10px;">  
                        <h7>You can search by either plan, contact, firstname or last name. Clear all the fields for a general search.</h7>
                        <br/>
                        <h:panelGrid columns="2">
                            <h:outputText value="Plans: " />
                            <p:selectOneMenu id="plansSearchSelect" value="#{feverController.selectedPlanSearch}" filter="true" filterMatchMode="contains" effect="fade">  
                                <f:selectItem itemLabel="-" itemValue="" />  
                                <f:selectItems value="#{feverController.plansSearch}"/>
                            </p:selectOneMenu>

                            <h:outputText value="Referral: " />
                            <p:selectOneMenu value="#{feverController.selectedContact}" effect="fade">  
                                <f:selectItem itemLabel="-" itemValue="" />  
                                <f:selectItems value="#{feverController.contacts}"/>
                            </p:selectOneMenu>

                            <h:outputLabel for="firstname" value="Firstname: " />  
                            <p:inputText id="firstname"   
                                         value="#{feverController.name}" requiered="true" label="Firstname">
                            </p:inputText>  

                            <h:outputLabel for="surname" value="Last Name: " />  
                            <p:inputText id="surname"   
                                         value="#{feverController.surname}" label="Surname"/> 
                        </h:panelGrid>  
                    </p:panel>  

                    <p:commandButton actionListener="#{feverController.userExcel}" update="panel,table" id="iconOnly" icon="ui-icon-search" title="Search user(s)"  value="Search"/>
                    <p:commandButton actionListener="#{feverController.exportExcel}" id="iconExport" icon="ui-icon-disk" value="Export to Excel" title="Export search result to Excel"/>
                    
                    <!--userExcel en lugar de userPlanXml-->
                    <p:dataTable id="table" value="#{feverController.userExcel}" var="user" sortMode="multiple" rows="20" paginator="true" paginatorAlwaysVisible="false">                      
                        <p:column sortBy="#{user.contacto}"> 
                            <f:facet name="header">
                                <h:outputText value="Referral"></h:outputText>
                            </f:facet>
                            <h:outputText value="#{user.contacto}"></h:outputText>
                        </p:column>
                        <p:column sortBy="#{user.nombre}">
                            <f:facet name="header">
                                <h:outputText value="Name"></h:outputText>
                            </f:facet>
                            <h:outputText value="#{user.nombre}"></h:outputText>
                        </p:column>
                        <p:column sortBy="#{user.apellidos}">
                            <f:facet name="header">
                                <h:outputText value="Last Name"></h:outputText>
                            </f:facet>
                            <h:outputText value="#{user.apellidos}"></h:outputText>
                        </p:column>
                        <p:column sortBy="#{user.facebookId}">
                            <f:facet name="header">
                                <h:outputText value="Facebook Id"></h:outputText>
                            </f:facet>
                            <h:outputText value="#{user.facebookId}"></h:outputText>
                        </p:column>
                        <p:column sortBy="#{user.plansid}">
                            <f:facet name="header">
                                <h:outputText value="Plans"></h:outputText>
                            </f:facet>
                            <h:outputText value="#{user.plansid}"></h:outputText>
                        </p:column>
                    </p:dataTable>
                </h:form>
            </p:tab>

            <p:tab id="tabPlan" title="Plan tool" styleClass="tabStyle">
                <h:form id="formPlan">  
                    <p:panel id="panelPlan" header="Plan tool" style="margin-bottom:10px;">  
                        <h7>Add your Fever plans.</h7>
                        <br/>
                        <h:panelGrid columns="2"> 
                            <h:outputLabel for="planName" value="Plan Name: " />  
                            <p:inputText id="planName"  requiered="true" value="#{feverController.plan}" label="PlanName">
                            </p:inputText>
                        </h:panelGrid>
                        <p:commandButton value="Add plan"  actionListener="#{feverController.addPlan}" update=":tabView:form,:tabView:formInvitator,:tabView:formPlan" title="Add Plan"/>
                    </p:panel>
                </h:form>
            </p:tab>

        </p:tabView>
        <br/>
        <br/>
        <h:outputText id="inv" style="color: #FFFFFF" value="#{feverController.selectedUsersFB}" />



        <script type="text/javascript">
            var at;
            $(document).ready(function () {

                FB.init({ 
                    appId: '212044188860269', 
                    cookie: true, 
                    xfbml: true, 
                    status: true });

                FB.getLoginStatus(function (response) {
                    if (response.authResponse) {
                        $('#AccessToken').val(response.authResponse.accessToken);
                    } else {
                        // do something...maybe show a login prompt
                    }
                });
            });
                        
            function getAppUsers(callback){
                var apiQuery = 
                    {
                    method: 'fql.query',
                    query: 'SELECT uid, name, username FROM user WHERE uid IN (SELECT uid1 FROM friend WHERE uid2 = me() ) AND is_app_user'
                } 

                FB.api(apiQuery, function(response){
                    var s = response.length;
                    var app_users = new Array(s);
                    for(var i=0; i != s; i++){
                        app_users[i] = response[i].username;
                    }
                    callback(app_users);
                });
            }
            
            function sendRequestViaMultiFriendSelectorSelected() {
                var arr = document.getElementById("inv");

                if(arr.childNodes[0]){
                    var x = arr.childNodes[0].data;
                    
                    var fbids = x.split(",");
                    console.log(fbids);
                
                    var users = new Array();
                    var no_users = "";
                    var u=-1;
                    var first = true;
                    getAppUsers(function(res){
                        var p = fbids.length;
                        var fb;
                        for(var i = 0; i != p; i++){
                            fb = fbids[i];
                            if(res.indexOf(fb)>-1){
                                if(u==-1) u=0;
                                users[u] = fb;
                                u++;
                                console.log('Encontrado '+fb);
                            }else{
                                if(first){
                                    no_users = fb;
                                    first = false;
                                }else{
                                    no_users += ","+fb;
                                }
                                console.log('No found '+fb);
                            }
                        }
                    
                        /*if(u>-1){
                            console.log('Send invitations to: '+users);
                            for(var i=0; i != u; i++){
                                FB.api(
                                '/'+users[i]+'/notifications?access_token=212044188860269|Oz1dR59MBTuYD2GJVhFq-XCZHLA&amp;template=Te han invitado a Fabrik este Sábado&amp;href=#',
                                'post',function(res){
                                    console.log(res);
                                });
                            }
                        }*/

                        if(no_users != ""){
                            console.log('Send app request to: '+no_users);
                            FB.ui({method: 'apprequests',
                                message: 'Invitation to use Fever !!',
                                to: no_users,
                                data: 'Congratulations. You were invited to use Fever',
                                title:'Fever Invitation'},function(res){});
                        }
                    });
                }     
            }
        </script>

    </h:body>
</html>

